package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ArticleCollectService;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thread.AppThreadLocalUtil;

@Service
public class ArticleCollectServiceImpl implements ArticleCollectService {
    @Autowired
    private CacheService cacheService;

    /**
     * 文章收藏
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {
        //条件判断
        if (dto == null || dto.getEntryId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断是否登录
        ApUser user = AppThreadLocalUtil.getApUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //查询
        String collection = (String) cacheService.hGet("COLLECTIONBEHAVIOR_" + user.getId(), dto.getEntryId().toString());
        if (StringUtils.isNotBlank(collection) && dto.getOperation() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已收藏");
        }

        //收藏
        if (dto.getOperation() == 0) {
            cacheService.hPut("COLLECTIONBEHAVIOR_" + user.getId(), dto.getEntryId().toString(), JSON.toJSONString(dto));
        } else {
            //取消收藏
            cacheService.hDelete("COLLECTIONBEHAVIOR_" + user.getId(), dto.getEntryId().toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
